package com.woniuxy.house.web;

import com.woniuxy.house.entity.Search;
import com.woniuxy.house.entity.Source;
import com.woniuxy.house.entity.User;
import com.woniuxy.house.service.SearchService;
import com.woniuxy.house.utils.JwtUtil;
import com.woniuxy.house.vo.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.ServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private SearchService searchService;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 根据搜索框内输入的内容模糊查找
     */
    @RequestMapping("/searchSourceBySearchText")
    public ResponseEntity searchSourceBySearchText(String searchText, ServletWebRequest request) {


        if (searchText == null || searchText.equals("")) {
            return ResponseEntity.NO_VALID;
        }
        //获取用户ID
        String jwt = request.getHeader("jwt");
        int id = (int) jwtUtil.verifyJWTGetUserId(jwt, "id");
        searchService.getByUserId(id);
        User user = new User();
        user.setId(id);
        //向数据库中增加搜索记录
        Search search = new Search();
        search.setContent(searchText);
        search.setUser(user);
        search.setTime(LocalDateTime.now());
        searchService.addSearch(search);
        //搜索输入内容相关房源
        List<Source> sources = searchService.getBySearchText(searchText);
        if (sources.size() == 0) {
            return new ResponseEntity<>("404", "未找到相关房源", null);
        }
        return new ResponseEntity<>("200", "ok", sources);
    }

    /**
     * 根据用户ID查找搜索记录
     */
    @RequestMapping("/getSearchByUserId")
    public ResponseEntity getSearchByUserId(ServletWebRequest request) {
        String jwt = request.getHeader("jwt");
        int id = (int) jwtUtil.verifyJWTGetUserId(jwt, "id");

        return new ResponseEntity<>("200", "ok", searchService.getByUserId(id));
    }

    /**
     * 获得热搜(参数限制个数)
     */
    @RequestMapping("/getHottestSearchLimitSize")
    public ResponseEntity getHottestSearchLimitSize(Integer size) {
        if (size == null) {
            return ResponseEntity.NO_VALID;
        }
        return new ResponseEntity<>("200", "ok", searchService.getHottestSearchLimitSize(size));
    }
}
